<template>
  <div class="order-page">

    <!-- 查询条件区域 -->
    <div class="order-query-card">
      <el-form :inline="true" ref="queryRef" :model="queryForm" class="order-query-form">
        <el-form-item label="搜索">
          <el-select v-model="searchType" placeholder="请选择搜索类型" style="width: 150px;">
            <el-option label="订单编号" value="orderNo"></el-option>
            <el-option label="用户姓名" value="username"></el-option>
            <el-option label="手机号" value="userPhone"></el-option>
            <!-- <el-option label="收货人手机" value="receiverPhone"></el-option> -->
            <!-- <el-option label="提货码" value="pickupCode"></el-option>
            <el-option label="物流单号" value="logisticsNo"></el-option>
            <el-option label="客户昵称" value="nickname"></el-option>
            <el-option label="规格编码" value="specCode"></el-option> -->
          </el-select>
          <el-input
            v-model="searchValue"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
            style="width: 200px; margin-left: 10px;"
          />
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select v-model="queryForm.orderType" placeholder="请选择订单类型" clearable class="order-select">
            <el-option v-for="item in orderTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付状态">
          <el-select v-model="queryForm.payStatus" placeholder="请选择支付状态" clearable class="order-select">
            <el-option v-for="item in payStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <div class="block" style="margin-right: 10px; display: inline-block;">
            <el-date-picker
              v-model="queryForm.orderTime"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
          <el-button type="primary" plain @click="selectToday">今日</el-button>
          <el-button type="primary" plain @click="selectYesterday">昨日</el-button>
          <el-button type="primary" plain @click="selectLast7Days">近7天</el-button>
          <el-button type="primary" plain @click="selectLast30Days">近30天</el-button>
        </el-form-item>
        <el-form-item class="order-form-btns">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单状态筛选 -->
    <div class="order-status-tabs">
      <el-tabs v-model="orderStates" @tab-click="handleTabClick" type="card">
        <el-tab-pane label="全部订单" name="0"/>
        <el-tab-pane label="待付款" name="1" />
        <el-tab-pane label="待发货" name="2" />
        <el-tab-pane label="部分发货" name="3" />
        <el-tab-pane label="已发货" name="4" />
        <el-tab-pane label="已完成" name="5" />
        <el-tab-pane label="已关闭" name="6" />
        <el-tab-pane label="售后中" name="7" />
      </el-tabs>
    </div>
    <!-- 订单表格 -->
    <div class="order-table-card">
      <div class="order-table-toolbar">
        <!-- 工具栏保持不变 -->
        <el-button type="primary" icon="el-icon-download" @click="handleExport" size="small">导出</el-button>
        <el-button type="danger" :disabled="!multipleSelection.length" @click="handleBatchDelete" size="small">批量删除</el-button>
        <el-button type="info" @click="testPagination" size="small">测试分页</el-button>
      </div>

      <el-table :data="orderList" border style="width: 100%;" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="商品" width="160" align="left">
          <template #default="scope">
            <div style="display: flex; align-items: center;">
              <img :src="scope.row.imgUrl" :width="50" :height="50"/>
              <div>
                <div>{{ scope.row.productName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="单价/数量" width="120" align="center">
          <template #default="scope">
            <div>￥{{ scope.row.productPrice }}</div>
            <div style="margin-left: 30px;">×{{ scope.row.productNum }}</div>
          </template>
        </el-table-column>
        <el-table-column label="订单编号" align="center" prop="orderNo" />
        <el-table-column label="用户名" align="center" prop="username" />
        <el-table-column label="手机号" align="center" prop="userPhone" />
        <el-table-column label="售后状态" width="100" align="center">
          <template #default="scope">{{ scope.row.salesStates }}</template>
        </el-table-column>
        <el-table-column label="订单金额" width="100" align="center">
          <template #default="scope">
            ￥{{ scope.row.orderMoney}}<br>
            <el-button type="text" size="small" v-if="scope.row.orderStates == 1" style="color: #409EFF;"  @click="handlePriceChange(scope.row)">改价</el-button>
          </template>
          
        </el-table-column>
        <el-table-column label="下单时间" align="center" prop="orderTime" />
        <el-table-column label="订单状态" width="100" align="center">
          <template #default="scope">
            <span :class="{'text-primary': scope.row.orderStates === '待付款'}">{{ scope.row.orderStates}}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleDetail(scope.row)">订单详情</el-button>
            <el-button type="text" size="small" style="color: #F56C6C;" @click="handleCancel(scope.row)">取消订单</el-button>
            <el-button type="text" size="small" @click="handleAddressChange(scope.row)">修改地址</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <div class="order-pagination">
        <el-pagination
          background
          :total="total"
          v-model:page="page.pageSize"
          v-model:limit="page.pageNum"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          :page-sizes="[10, 20, 50, 100]"
          :hide-on-single-page="false"
        />
      </div>
    </div>
  </div>

  <!-- 订单详情弹窗 -->
  <el-dialog v-model="detailDialogVisible" :title="detailDialogTitle" width="900px" :close-on-click-modal="false" @close="closeDetailDialog" class="order-detail-dialog">
    <el-scrollbar height="520px">
      <div class="order-detail-section">
        <div class="order-detail-block">
          <div class="order-detail-title">基础信息</div>
          <el-descriptions :column="2" border v-loading="detailLoading" class="order-detail-desc">
            <el-descriptions-item label="订单编号">{{ orderDetail.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">{{ orderDetail.orderStates }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ formatDate(orderDetail.orderTime) }}</el-descriptions-item>
            <el-descriptions-item label="要求送达时间">{{ formatDate(orderDetail.requiredDeliveryTime) }}</el-descriptions-item>
            <el-descriptions-item label="收货人姓名">{{ orderDetail.receiverName }}</el-descriptions-item>
            <el-descriptions-item label="收货人电话">{{ orderDetail.receiverPhone }}</el-descriptions-item>
            <el-descriptions-item label="详细地址" :span="2">{{ orderDetail.detailAddress }}</el-descriptions-item>
            <el-descriptions-item label="支付状态">{{ orderDetail.payStatus }}</el-descriptions-item>
            <el-descriptions-item label="订单类型">{{ orderDetail.orderType }}</el-descriptions-item>
            <el-descriptions-item label="支付方式">{{ orderDetail.payMethod }}</el-descriptions-item>
            <el-descriptions-item label="支付金额">￥{{ orderDetail.orderMoney }}</el-descriptions-item>
            <el-descriptions-item label="支付时间">{{ formatDate(orderDetail.payTime) }}</el-descriptions-item>
            <el-descriptions-item label="配送费">{{ orderDetail.deliveryFee }}</el-descriptions-item>
            <el-descriptions-item label="优惠金额">{{ orderDetail.discountAmount }}</el-descriptions-item>
            <el-descriptions-item label="商品金额">{{ orderDetail.goodsAmount }}</el-descriptions-item>
            <el-descriptions-item label="总金额">￥{{ orderDetail.orderMoney }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ orderDetail.remark }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div v-if="orderDetail && orderDetail.orderItemList && orderDetail.orderItemList.length" class="order-detail-block">
          <div class="order-detail-title">商品明细</div>
          <el-table :data="orderDetail.orderItemList" border size="small" stripe class="order-detail-table">
            <el-table-column label="商品图片" width="80" align="center">
              <template #default="scope">
                <el-image :src="scope.row.imgUrl" style="width:60px;height:60px;object-fit:cover;border-radius:6px;cursor:pointer;" @click.stop="openImageDialog(scope.row)" preview-src-list="[]">
                  <template #error>
                    <div style="width:60px;height:60px;display:flex;align-items:center;justify-content:center;background:#f2f2f2;color:#bbb;font-size:12px;">无图</div>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="productName" align="center"/>
            <el-table-column label="商品售价" prop="sellingPrice" align="center"/>
            <el-table-column label="购买数量" prop="productNum" align="center" />
            <el-table-column label="优惠金额" prop="discountMoney" align="center" />
            <el-table-column label="单位" prop="unit" align="center" />
            <el-table-column label="商品总价" prop="totalPrice" align="center" />
          </el-table>
        </div>
      </div>
    </el-scrollbar>
    <template #footer>
      <el-button @click="closeDetailDialog">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 商品图片弹窗 -->
  <el-dialog v-model="imageDialogVisible" width="420px" :show-close="true" :close-on-click-modal="true" title="商品图片" class="product-image-dialog">
    <div v-if="imageDialogRow">
      <el-image :src="imageDialogRow.mainImage" style="width:320px;height:320px;object-fit:contain;display:block;margin:0 auto 18px auto;background:#f8f8f8;border-radius:8px;" />
      <div class="product-image-info">
        <div><b>商品名称：</b>{{ imageDialogRow.itemName }}</div>
        <div><b>商品规格：</b>{{ imageDialogRow.productSpec }}</div>
        <div><b>商品重量：</b>{{ imageDialogRow.weight ? imageDialogRow.weight + ' kg' : '-' }}</div>
        <div><b>数量：</b>{{ imageDialogRow.quantity }}</div>
        <div><b>单位：</b>{{ imageDialogRow.unit }}</div>
        <div><b>单价：</b>{{ imageDialogRow.salePrice }}</div>
        <div><b>总价：</b>{{ imageDialogRow.totalPrice }}</div>
      </div>
    </div>
  </el-dialog>

  <!--改价弹窗-->
  <el-dialog v-model="priceChangeDialogVisible" title="改价" width="800px" :close-on-click-modal="false">
    <el-form :model="priceChangeForm" label-width="80px">
      <el-form-item label="订单原价">
          {{ priceChangeForm.originalPrice }}
        </el-form-item>
      <el-form-item label="一键改价">
        <el-input v-model="priceChangeForm.oneKeyPriceChange" placeholder="请输入" style="width: 150px;" />
        <span style="margin-left: 10px;">元</span>
      </el-form-item>
      
      <el-table :data="priceChangeForm.productList" border size="small" style="margin: 20px 0;">
          <el-table-column label="商品" prop="productName" width="200" />
          <el-table-column label="单价" prop="sellingPrice" width="100" align="right" />
          <el-table-column label="数量" prop="productNum" width="80" align="center" />
          <el-table-column label="优惠" prop="discountMoney" width="80" align="right" />
          <el-table-column label="当前价" prop="totalPrice" width="100" align="right" />
        <el-table-column label="涨价/降价" width="100" align="right">
          <template #default="scope">
            <el-input v-model="scope.row.priceAdjustment" size="small" style="width: 80px;" />
          </template>
        </el-table-column>
        <el-table-column label="改后金额" width="100" align="right">
          <template #default="scope">
            {{ ((Number(scope.row.sellingPrice) + Number(scope.row.priceAdjustment || 0)) * Number(scope.row.productNum)).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
      
      <el-form-item label="运费">
        <el-input v-model="priceChangeForm.freight" style="width: 150px;" />
        <span style="margin-left: 10px;">元</span>
        <el-button type="text" @click="priceChangeForm.freight = 0" style="margin-left: 20px;">直接免运费</el-button>
      </el-form-item>
      
      <el-form-item label="买家实付">
        ￥{{ priceChangeForm.finalPrice }}
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="priceChangeDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmPriceChange">确定</el-button>
    </template>
  </el-dialog>

  <!--修改地址-->
  <el-dialog v-model="address" title="修改地址" width="500">
    <el-form :model="updForm">
      <el-form-item label="收货人" :label-width="formLabelWidth" style="margin-left: 30px;">
        <el-input v-model="updForm.receiverName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="收货人电话" :label-width="formLabelWidth">
        <el-input v-model="updForm.receiverPhone" autocomplete="off" />
      </el-form-item>
      <!-- <el-form-item label="收货人地址" :label-width="formLabelWidth">
        <el-cascader
          v-model="value"
          :options="options"
          :props="props"
          placeholder="请选择地址"
          @change="handleChange"
          style="width: 270px"
        />
      </el-form-item> -->
      <el-form-item label="收货人地址" :label-width="formLabelWidth">
        <el-input v-model="updForm.detailAddress" autocomplete="off" />
      </el-form-item>
      <el-form-item label="门牌号" :label-width="formLabelWidth" style="margin-left: 30px;">
        <el-input v-model="updForm.houseNumber" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="address = false">取消</el-button>
        <el-button type="primary" @click="submit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import dayjs from 'dayjs'
import { fetchOrderList, fetchOrderDetail, deleteOrders, exportOrderList, updateAddress, updatePrice } from '@/api/order/orderList'
import { ElMessageBox, ElMessage } from 'element-plus'
import { toRaw } from 'vue'

const orderStates = ref(0)
const loading = ref(false)
const updForm = ref({
  id: '',
  receiverName: '',
  receiverPhone: '',
  detailAddress: '',
  houseNumber: ''
})
const orderList = ref([])
const address = ref(false)
const total = ref(0)
const page = ref({
  pageNum: 1, 
  pageSize: 10
})

const searchType = ref('')
const searchValue = ref('')
const queryForm = ref({
  orderType: '',
  payStatus: '',
  orderTime: []
})

const orderTypeOptions = [
  { label: '全部', value: '' },
  { label: '配送', value: 1 },
  { label: '自提', value: 2 }
]
const payStatusOptions = [
  { label: '全部', value: '' },
  { label: '未支付', value: 1 },
  { label: '已完成', value: 8 },
  { label: '已退款', value: 9 }
]

function orderTypeText(type) {
  if (type === 1) return '外卖'
  if (type === 2) return '自提'
  return '-'
}


// 获取当前实例
const { proxy } = getCurrentInstance()

// 快捷时间选择函数
function selectToday() {
  const start = dayjs().startOf('day')
  const end = dayjs().endOf('day')
  queryForm.value.orderTime = [start, end]
  handleQuery()
}

function selectYesterday() {
  const start = dayjs().subtract(1, 'day').startOf('day')
  const end = dayjs().subtract(1, 'day').endOf('day')
  queryForm.value.orderTime = [start, end]
  handleQuery()
}

function selectLast7Days() {
  const start = dayjs().subtract(7, 'day').startOf('day')
  const end = dayjs().endOf('day')
  queryForm.value.orderTime = [start, end]
  handleQuery()
}

function selectLast30Days() {
  const start = dayjs().subtract(30, 'day').startOf('day')
  const end = dayjs().endOf('day')
  queryForm.value.orderTime = [start, end]
  handleQuery()
}

function loadOrders() {
  loading.value = true
  const params = {
    pageNum: page.value.pageNum,
    pageSize: page.value.pageSize,
    orderType: queryForm.value.orderType,
    paymentStatus: queryForm.value.payStatus,
    createTimeStart: queryForm.value.orderTime[0] ? dayjs(queryForm.value.orderTime[0]).format('YYYY-MM-DD HH:mm:ss') : '',
    createTimeEnd: queryForm.value.orderTime[1] ? dayjs(queryForm.value.orderTime[1]).format('YYYY-MM-DD HH:mm:ss') : '',
    orderStates: orderStates.value
  }
  console.log(params.createTimeStart)
  console.log(params.createTimeEnd)
  // 添加动态搜索参数
  if (searchType.value && searchValue.value) {
    params[searchType.value] = searchValue.value
  }
  
  fetchOrderList(params)
    .then(res => {
      orderList.value = res.rows || []
      total.value = res.total || 0
      console.log(res)
    })
    .finally(() => {
      loading.value = false
    })
}

//修改地址
async function handleAddressChange(row) {
  address.value = true
  updForm.value = row
}
//修改地址
function submit(){
  const rawData = toRaw(updForm.value);
  updateAddress(rawData).then(res => {
    ElMessage.success(res.message)
    address = false
    loadOrders()
  })
}

function handleQuery() {
  page.value.pageNum = 1
  // 重置所有搜索参数
  Object.keys(queryForm.value).forEach(key => {
    if (!['orderType', 'payStatus', 'orderTime'].includes(key)) {
      queryForm.value[key] = null;
    }
  });
  // 设置当前选择的搜索参数
  if (searchType.value && searchValue.value) {
    queryForm.value[searchType.value] = searchValue.value;
  }
  loadOrders()
}
function handleReset() {
  searchType.value = ''
  searchValue.value = ''
  queryForm.value = {
    orderType: '',
    payStatus: '',
    orderTime: []
  }
  // 重置表单引用
  const queryRef = proxy?.$refs.queryRef
  if (queryRef) {
    queryRef.resetFields()
  }
  page.value.pageNum = 1
  loadOrders()
}
function handleTabClick(tab) {
  orderStates.value = tab.paneName
  page.value.pageNum = 1
  loadOrders()
}
function handleSizeChange(size) {
  console.log('改变每页显示数量:', size)
  page.value.pageSize = size
  page.value.pageNum = 1
  loadOrders()
}

function handlePageChange(num) {
  console.log('改变当前页码:', num)
  page.value.pageNum = num
  loadOrders()
}

// 添加分页状态监听
import { watch } from 'vue'

watch(() => page.value, (newPage) => {
  console.log('分页状态变化:', newPage)
}, { deep: true })

// 测试分页功能
function testPagination() {
  console.log('当前分页状态:', page.value)
  console.log('当前订单列表长度:', orderList.value.length)
  console.log('订单列表数据:', orderList.value)
  
  // 模拟API响应格式测试
  const mockResponse = {
    records: orderList.value,
    total: orderList.value.length,
    current: page.value.pageNum,
    size: page.value.pageSize
  }
  console.log('模拟的标准分页响应格式:', mockResponse)
  
  ElMessage.info(`当前页码: ${page.value.pageNum}, 每页数量: ${page.value.pageSize}, 总数: ${page.value.total}, 列表长度: ${orderList.value.length}`)
}

// 详情弹窗相关
const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const orderDetail = ref({})

// 改价弹窗相关
const priceChangeDialogVisible = ref(false)
const priceChangeForm = ref({
  originalPrice: 0,
  newTotalPrice: 0,
  productList: [],
  freight: 0,
  finalPrice: 0,
  changeMoney: 0
})

// 监听商品价格调整和运费变化，计算最终价格
    watch(
      () => [priceChangeForm.value.productList, priceChangeForm.value.freight],
      ([products, freight]) => {
        let total = 0
        products.forEach(item => {
          // 改后金额 = (单价 + 涨价/降价) × 数量
          const adjustedPrice = Number(item.sellingPrice) + Number(item.priceAdjustment || 0)
          total += adjustedPrice * Number(item.productNum)
        })
        priceChangeForm.value.finalPrice = (total + Number(freight || 0)).toFixed(2)
      },
      { deep: true }
    )

// 监听一键改价输入，直接应用到所有商品
    watch(
      () => priceChangeForm.value.oneKeyPriceChange,
      (newValue) => {
        if (newValue === null || newValue === undefined || newValue === '') {
          return;
        }
        if (priceChangeForm.value.productList.length) {
          // 直接将输入值应用到所有商品的涨价/降价字段
          priceChangeForm.value.productList.forEach(item => {
            item.priceAdjustment = Number(newValue).toFixed(2)
          })
        }
      }
    )

const detailDialogTitle = computed(() => {
  if (!orderDetail.value) return '订单详情'
  return `订单详情 - ${orderDetail.value.orderNo || ''} ${orderDetail.value.customerName ? '（' + orderDetail.value.customerName + '）' : ''}`
})

async function handleDetail(row) {
  detailDialogVisible.value = true
  detailLoading.value = true
  try {
    const res = await fetchOrderDetail(row.id)
    console.log(res)
    orderDetail.value = res || {}
  } finally {
    detailLoading.value = false
  }
}

function closeDetailDialog() {
  detailDialogVisible.value = false
  orderDetail.value = {}
}

async function handleCancel(row) {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    // TODO: 调用取消订单接口
    // await cancelOrderApi(row.id)
    ElMessage.success('订单已取消（模拟）')
    loadOrders()
  } catch (e) {
    // 用户取消操作，无需处理
  }
}

async function handlePriceChange(row) {
  try {
    // 先获取订单详情
    detailLoading.value = true
    const res = await fetchOrderDetail(row.id)
    orderDetail.value = res || {}
    detailLoading.value = false
    
    // 初始化改价表单
    priceChangeForm.value = {
      originalPrice: Number(res.orderMoney || 0).toFixed(2),
      oneKeyPriceChange: '',
      productList: (res.orderItemList || []).map(item => ({
        ...item,
        productName: item.productName,
        sellingPrice: Number(item.sellingPrice || 0).toFixed(2),
        productNum: item.productNum,
        discountMoney: Number(item.discountMoney || 0).toFixed(2),
        totalPrice: Number(item.totalPrice || 0).toFixed(2),
        priceAdjustment: '0',
        // 改后金额 = (单价 + 涨价/降价) × 数量
        changeMoney: (Number(item.sellingPrice) + Number(item.priceAdjustment || 0)) * Number(item.productNum)
      })),
      freight: '0', // 运费默认设置为10
      finalPrice: '0'
    }
    console.log(priceChangeForm.value)
    
    // 计算初始最终价格
    let total = 0
    priceChangeForm.value.productList.forEach(item => {
      // 直接使用changeMoney字段的值
      total += Number(item.changeMoney)
    })
    priceChangeForm.value.finalPrice = (total + Number(priceChangeForm.value.freight)).toFixed(2)
    
    // 打开改价弹窗
    priceChangeDialogVisible.value = true
  } catch (e) {
    detailLoading.value = false
    // 用户取消操作，无需处理
  }

  // 监听商品价格调整变化，自动更新改后金额
  watch(() => priceChangeForm.value.productList, (newVal) => {
    if (newVal) {
      newVal.forEach(item => {
        item.changeMoney = (Number(item.sellingPrice) + Number(item.priceAdjustment || 0)) * Number(item.productNum)
      })
      // 重新计算最终价格
      let total = 0
      newVal.forEach(item => {
        total += Number(item.changeMoney)
      })
      priceChangeForm.value.finalPrice = (total + Number(priceChangeForm.value.freight)).toFixed(2)
    }
  }, { deep: true })
}

async function confirmPriceChange() {
  try {
    // 收集改价数据
    const priceData = {
      orderId: orderDetail.value.id,
      orderMoney: priceChangeForm.value.originalPrice,//订单原价
      finalPrice: priceChangeForm.value.finalPrice,//买家实付
      freight: priceChangeForm.value.freight,//运费
      productList: priceChangeForm.value.productList
    }
    console.log('改价数据:', priceData)
    
    // TODO: 调用改价接口
    await updatePrice(priceData)
    
    ElMessage.success('改价成功')
    priceChangeDialogVisible.value = false
    loadOrders() // 重新加载订单列表
  } catch (e) {
    ElMessage.error('改价失败: ' + (e.message || '未知错误'))
  }
}

function formatDate(val) {
  if (!val) return '-'
  return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
}

const imageDialogVisible = ref(false)
const imageDialogRow = ref(null)
function openImageDialog(row) {
  imageDialogRow.value = row
  imageDialogVisible.value = true
}

const multipleSelection = ref([])
function handleSelectionChange(val) {
  multipleSelection.value = val
}
async function handleDelete(row) {
  try {
    await ElMessageBox.confirm('确定要删除该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteOrders([row.id])
    ElMessage.success('删除成功')
    loadOrders()
  } catch (e) {}
}
async function handleBatchDelete() {
  if (!multipleSelection.value.length) return
  try {
    await ElMessageBox.confirm('确定要删除选中的订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteOrders(multipleSelection.value.map(item => item.id))
    ElMessage.success('批量删除成功')
    loadOrders()
  } catch (e) {}
}

async function handleExport() {
  const params = {
    orderType: queryForm.value.orderType,
    paymentStatus: queryForm.value.payStatus,
    createTimeStart: queryForm.value.orderTime[0] ? dayjs(queryForm.value.orderTime[0]).format('YYYY-MM-DD HH:mm:ss') : '',
    createTimeEnd: queryForm.value.orderTime[1] ? dayjs(queryForm.value.orderTime[1]).format('YYYY-MM-DD HH:mm:ss') : '',
    orderStates: orderStates.value,
    pageNum: undefined, // 导出全部，不分页
    pageSize: undefined
  }
  // 添加动态搜索参数
  if (searchType.value && searchValue.value) {
    params[searchType.value] = searchValue.value
  }
  const res = await exportOrderList(params)
  const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', '订单导出.xlsx')
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped lang="scss">
.order-page {
  padding: 32px 24px;
  background: #f5f7fa;
  min-height: 100vh;
}
.order-status-tabs {
  margin-bottom: 18px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  padding: 8px 16px 0 16px;
}
.order-query-card {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  padding: 18px 24px 6px 24px;
  margin-bottom: 18px;
}
.order-query-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px 32px;
}
.order-query-form .el-form-item {
  margin-bottom: 0;
}
.order-input,
.order-select,
.order-date-picker {
  width: 180px;
  border-radius: 6px;
}
.order-date-picker {
  width: 240px;
}
.order-form-btns {
  display: flex;
  align-items: center;
  gap: 8px;
}
.order-form-btns .el-button:first-child {
  box-shadow: 0 2px 8px rgba(24,144,255,0.08);
}
.order-table-card {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  padding: 18px 0 0 0;
}
.order-table-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
}
.order-detail-btn {
  font-weight: 500;
  letter-spacing: 1px;
  padding: 0 18px;
}
.order-pagination {
  display: flex;
  justify-content: flex-end;
  padding: 18px 24px 18px 0;
}
.order-detail-dialog {
  .el-dialog__body {
    padding: 24px 32px 8px 32px;
    background: #f8fafc;
  }
}
.order-detail-section {
  display: flex;
  flex-direction: column;
  gap: 32px;
}
.order-detail-block {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 18px 24px 12px 24px;
}
.order-detail-title {
  font-size: 17px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 16px;
  letter-spacing: 1px;
}
.order-detail-desc {
  background: #f9f9fb;
  border-radius: 6px;
  padding: 8px 0;
}
.order-detail-table {
  margin-top: 8px;
  border-radius: 6px;
  font-size: 14px;
}
.product-image-dialog {
  .el-dialog__body {
    padding: 24px 24px 12px 24px;
    background: #f8fafc;
  }
}
.product-image-info {
  font-size: 15px;
  color: #333;
  line-height: 2.1;
  padding: 0 8px;
}
</style>